<template>
  <custom-container ref="customContainerRef" :config="config" />
  <!-- 新增-修改重量进位规则弹出框 -->
  <div>
    <el-dialog
      v-model="open"
      :title="title"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        ref="editform"
        label-width="120px"
        class="queryParams"
        inline
        :model="form"
        :rules="rules"
      >
        <el-form-item label="国家" prop="country">
          <el-select v-model="form.country" filterable clearable>
            <el-option
              v-for="dict in dicts[DictDirection.国家]"
              :key="dict.countryCode"
              :label="dict.countryChName"
              :value="dict.countryCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="货物类型" prop="goods">
          <el-select v-model="form.goods" filterable clearable>
            <el-option
              v-for="dict in dicts[DictDirection.包裹类型]"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下线重量" prop="lowerWeight">
          <el-input-number
            v-model="form.lowerWeight"
            controls-position="right"
            :step="0.01"
            :min="0"
            clearable
          ></el-input-number>
        </el-form-item>
        <el-form-item label="上限重量" prop="upperWeight">
          <el-input-number
            v-model="form.upperWeight"
            controls-position="right"
            :step="0.01"
            :min="0"
            clearable
          ></el-input-number>
        </el-form-item>
        <el-form-item label="进位规则" prop="carryType">
          <el-select v-model="form.carryType" filterable clearable>
            <el-option
              v-for="item in carryTypeDicts"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规则值" prop="carryRules">
          <el-input-number
            v-model="form.carryRules"
            :max="1"
            :min="0"
            controls-position="right"
            :step="0.1"
            clearable
          ></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dicts[DictDirection.通用状态]" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="submitform">确定</el-button>
          <el-button @click="cancelweightRlues">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { Delete, Plus, Edit } from '@element-plus/icons-vue'
import {
  ref,
  getCurrentInstance,
  defineAsyncComponent,
  computed,
  defineProps,
  watch,
} from 'vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import userDicts, { DictDirection } from '@/store/modules/dicts'
import {
  getData,
  addData,
  delData,
  editData,
  getDataDetailed,
} from '@/api/BusinessConfig/productWeightServicechannel'

const dicts = userDicts()
dicts.setDicts(DictDirection.国家)
dicts.setDicts(DictDirection.收货站点)
dicts.setDicts(DictDirection.包裹类型)
const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('国家必须输入'))
  } else {
    callback()
  }
}
const props = defineProps<{
    productId:number,
    fatherOpen:boolean
}>()
// 查询参数
const
  queryParams = ref({
    pageSize: 10,
    pageNum: 1,
    id: undefined,
  }),
  // 选中数组
  // 非单个禁用
  single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  customContainerRef = ref(null),
  // 新增-修改弹出框
  open = ref(false),
  // 新增-修改标题
  title = ref(undefined),
  // 规则
  rules = {
    country: [
      {
        validator: validatePass,
        required: true,
        trigger: ['blur', 'change'],
      },
    ],
    goods: [
      {
        required: true,
        message: '国家必须输入',
        trigger: ['blur', 'change'],
      },
    ],
    lowerWeight: [
      {
        required: true,
        message: '下线重量必须输入',
        trigger: ['blur', 'change'],
      },
    ],
    upperWeight: [
      {
        required: true,
        message: '上限重量必须输入',
        trigger: ['blur', 'change'],
      },
    ],
    carryType: [
      {
        required: true,
        message: '进位类型必须输入',
        trigger: ['blur', 'change'],
      },
    ],
    carryRules: [
      {
        required: true,
        message: '规则值必须输入',
        trigger: ['blur', 'change'],
      },
    ],
  },
  carryTypeDicts = [
    { label: '重量进位', value: '1', key: 1 },
    { label: '四舍五入', value: '2', key: 2 },
  ],
  form = ref({
    id: undefined,
    goods: undefined,
    country: undefined,
    lowerWeight: undefined,
    upperWeight: undefined,
    carryType: undefined,
    carryRules: undefined,
    status: 1,
    salesProductId: undefined,
  }),
  editform = ref(null),
  {
    appContext: {
      config: {
        globalProperties: { $resetForm, $validateForm },
      },
    },
  } = getCurrentInstance()
  // 查询
const handleQuery = () => {
  queryParams.value.pageNum = 1
  customContainerRef.value.getList()
}
let ids = []
// 重置表单
const reset = () => {
  form.value = {
    id: undefined,
    goods: undefined,
    country: undefined,
    lowerWeight: undefined,
    upperWeight: undefined,
    carryType: undefined,
    carryRules: undefined,
    status: 1,
    salesProductId: undefined,
  }
  $resetForm(editform.value)
}
// 多选框选中数据
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  const rowsList = JSON.parse(JSON.stringify(rows))
  ids = rowsList.map((item) => item.id)
  single.value = rowsList.length != 1
  multiple.value = !rowsList.length
}
/** 新增按钮操作 */
const handleAdd = () => {
  open.value = true
  title.value = '新增重量进位规则'
}
/** 修改按钮操作 */
const handleUpdate = (row:{[key:string]:any}) => {
  const id = (row && row.id) || ids[0]
  getDataDetailed(id).then(res => {
    if (res.code == 200) {
      form.value = res.data
      open.value = true
      title.value = '修改重量进位规则'
    }
  })
}
/** 删除按钮操作 */
const handleDelete = (row: { [key: string]: any }) => {
  const rowList = JSON.parse(JSON.stringify(row))
  const id = rowList.id || ids
  ElMessageBox.confirm(`"是否确认删除产品代码为"${ id }"的数据项?"`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => delData(id))
  .then((res) => {
    if (res.code === 200) {
      handleQuery()
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => {
    if (error == 'cancel') {
      ElMessage.error(error)
    }
  })
}
// 确定-新增、修改
const submitform = () => {
  $validateForm(editform.value, () => {
    form.value.salesProductId = props.productId
    if (form.value.id != undefined) {
      editData(form.value).then((res) => {
        if (res.code == 200) {
          ElMessage.success('修改成功')
          handleQuery()
          reset()
          open.value = false
        }
      })
    } else {
      addData(form.value).then((res) => {
        if (res.code == 200) {
          ElMessage.success('新增成功')
          handleQuery()
          reset()
          open.value = false
        }
      })
    }
  })
}
// 取消新增-修改
const cancelweightRlues = () => {
  reset()
  open.value = false
}
const config = computed({
  get() {
    return {
      query: {
        fields: [],
        queryParams: queryParams.value,
      },
      btns: [
        {
          title: '新增',
          icon: Plus,
          directive: [['hasPermi', ['system:weightCarryRule:add']]],
          onClick: handleAdd,
        },
        {
          title: '修改',
          icon: Edit,
          disabled: single.value,
          directive: [['hasPermi', ['system:weightCarryRule:edit']]],

          onClick: handleUpdate,
          type: 'success',
        },
        {
          title: '删除',
          icon: Delete,
          onClick: handleDelete,
          directive: [['hasPermi', ['system:weightCarryRule:remove']]],
          type: 'danger',
        },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55', align: 'center' },
          {
            label: '序号',
            prop: 'id',
            align: 'center',
            width: '90',
          },
          {
            label: '国家',
            prop: 'country',
            align: 'center',
            width: '90',
            autoFormatter: {
              dict: DictDirection.国家,
              rowKey: 'country',
            },
           
          },
          {
            label: '货物类型',
            prop: 'goods',
            align: 'center',
            width: '90',
            autoFormatter: {
              dict: DictDirection.包裹类型,
              rowKey: 'goods',
            },
          },
          {
            label: '下线重量',
            prop: 'lowerWeight',
            align: 'center',
            width: '90',
          },
          {
            label: '上线重量',
            prop: 'upperWeight',
            align: 'center',
            width: '90',
          },
          {
            label: '进位规则',
            prop: 'carryType',
            align: 'center',
            width: '90',
            option: {
              dictInfo: {
                dict: [
                  { label: '重量进位', value: 1, id: 1 },
                  { label: '四舍五入', value: 2, id: 2 },
                ],
                dictValue: 'value',
                dictLabel: 'label',
              },
            },
          },
          {
            label: '规则值',
            prop: 'carryRules',
            align: 'center',
            width: '90',
          },
          {
            label: '状态',
            prop: 'status',
            align: 'center',
            width: '90',
            autoFormatter: {
              dict: DictDirection.通用状态,
              rowKey: 'status',
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleSelectionChange(rows)
          },
        },
      },
      api: getData,
      requestTrans: (q) => {
        q.id = props.productId
        queryParams.value = q
        return q
      },
    }
  },
  set(val) {
    return val
  },
})
</script>